﻿using BasicComponents.dialogs;
using BasicComponents.model;
using BasicComponents.utils;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace BasicComponents.com
{
    /// <summary>
    /// Window_MBTiaoJian.xaml 该类用于弹出一个弹窗配置设置某个字段的公式，使用是请实现getBackGsxx返回事件，用于返回设置好的条件信息
    /// </summary>
    public partial class Window_defineFormula : Window, INotifyPropertyChanged
    {
        StringBuilder sb_conditon = new StringBuilder();//公式内容，
        StringBuilder sb_gsForDisplay = new StringBuilder();//公式显示内容 
        bool isOk = false;
        bool isEdit = false;
        private string szResult;

        public event GetBackGsxx getBackGsxx;
        public event PropertyChangedEventHandler PropertyChanged;

        public delegate Boolean GetBackGsxx(String gsnr, String displayGs);

        ObservableCollection<ComboItemsResources> list_field = new ObservableCollection<ComboItemsResources>();//字段下拉框内容
        ObservableCollection<ComboItemsResources> list_tiaoJian = new ObservableCollection<ComboItemsResources>();//条件下拉框内容
        ObservableCollection<ComboItemsResources> list_luoJiGuanXi = new ObservableCollection<ComboItemsResources>();//逻辑关系下拉框内容
        ObservableCollection<MBGuiZe> list_MBGuiZe = new ObservableCollection<MBGuiZe>();//模板的规则表格的内容
        DataTable dialog_dmmc = new DataTable(); //选择科目弹窗的数据表，数据表中必须包含dm,mc两列。
        String dialog_fjfa = "99";//科目的分级方案
        public ObservableCollection<ComboItemsResources> List_field { get => list_field; set => list_field = value; }
        public ObservableCollection<ComboItemsResources> List_tiaoJian { get => list_tiaoJian; set => list_tiaoJian = value; }
        public ObservableCollection<ComboItemsResources> List_luoJiGuanXi { get => list_luoJiGuanXi; set => list_luoJiGuanXi = value; }
        public ObservableCollection<MBGuiZe> List_MBGuiZe { get => list_MBGuiZe; set => list_MBGuiZe = value; }
        public StringBuilder Sb_conditon { get => sb_conditon; set => sb_conditon = value; }//字段条件
        public StringBuilder Sb_gsForDisplay { get => sb_gsForDisplay; set => sb_gsForDisplay = value; }
        public bool IsOk { get; private set; }
        public bool IsEdit
        {
            get => isEdit; set
            {
                isEdit = value;

                if (PropertyChanged != null)
                {
                    PropertyChanged(this, new PropertyChangedEventArgs("IsEdit"));
                }
            }
        }

        /// <summary>
        /// 公式设置弹窗，设置完成后返回公式,需要实现getBackGsxx返回公式内容，gsnr(后台解析的真正公式内容),displayGs(便于阅读显示的公式内容)
        /// </summary>
        /// <param name="dictionaryConditionFileds">字段字典，key为代码，value为名称</param>
        /// <param name="gsnr">后台解析的真正公式内容</param>
        /// <param name="displayGs">便于阅读显示的公式内容</param>
        /// <param name="isEdit">是否允许编辑</param>
        public Window_defineFormula(Dictionary<String, String> dictionaryConditionFileds, String gsnr, String displayGs, Boolean isEdit)
        {
            InitializeComponent();
            this.btn_selectEle.Visibility = Visibility.Collapsed;
            this.sb_conditon.Append(gsnr);
            this.IsEdit = isEdit;
            this.DataContext = this;
            initFields(dictionaryConditionFileds);
            initLuoJI_TiaoJian();
            initgs(displayGs, gsnr);
            if (!isEdit)
            {
                this.lbox_gs.IsEnabled = true;
                this.dg_guize.IsReadOnly = true;
                this.tbox_result.IsReadOnly = true;
                this.btn_addTiaoJian.IsEnabled = false;
                this.btn_delTiaoJian.IsEnabled = false;
                this.btn_add.IsEnabled = false;
                this.btn_del.IsEnabled = false;
                this.btn_up.IsEnabled = false;
                this.btn_down.IsEnabled = false;
                this.btn_cancel.IsEnabled = false;
                this.btn_ok.IsEnabled = false;
                this.btn_saveAndBack.IsEnabled = false;
            }
        }
        /// <summary>
        /// 公式设置弹窗，设置完成后返回公式,需要实现getBackGsxx返回公式内容，gsnr(后台解析的真正公式内容),displayGs(便于阅读显示的公式内容)
        /// </summary>
        /// <param name="listConditionFileds">字段列表</param>
        /// <param name="gsnr">后台解析的真正公式内容</param>
        /// <param name="displayGs">便于阅读显示的公式内容</param>
        /// <param name="isEdit">是否允许编辑</param>
        public Window_defineFormula(List<String> listConditionFileds, String gsnr, String displayGs, Boolean isEdit)
        {
            InitializeComponent();
            LogPrinter.LogPrinter.printModDebugLog2File("Window_defineFormula(List<String> listConditionFileds, String gsnr, String displayGs, Boolean isEdit)被访问", "Window_defineFormula");
            this.btn_selectEle.Visibility = Visibility.Collapsed;
            this.sb_conditon.Append(gsnr);
            this.IsEdit = isEdit;
            this.DataContext = this;
            initFields(listConditionFileds);
            initLuoJI_TiaoJian();
            initgs(displayGs, gsnr);
            LogPrinter.LogPrinter.printModDebugLog2File("解析公式完成！", "Window_defineFormula");
            if (!isEdit)
            {
                this.lbox_gs.IsEnabled = true;
                this.dg_guize.IsReadOnly = true;
                this.tbox_result.IsReadOnly = true;
                this.btn_addTiaoJian.IsEnabled = false;
                this.btn_delTiaoJian.IsEnabled = false;
                this.btn_add.IsEnabled = false;
                this.btn_del.IsEnabled = false;
                this.btn_up.IsEnabled = false;
                this.btn_down.IsEnabled = false;
                this.btn_cancel.IsEnabled = false;
                this.btn_ok.IsEnabled = false;
                this.btn_saveAndBack.IsEnabled = false;
            }
        }

        /// <summary>
        /// 公式设置弹窗，设置完成后返回公式,需要实现getBackGsxx返回公式内容，gsnr(后台解析的真正公式内容),displayGs(便于阅读显示的公式内容)
        /// </summary>
        /// <param name="listConditionFileds">字段列表</param>
        /// <param name="gsnr">后台解析的真正公式内容</param>
        /// <param name="displayGs">便于阅读显示的公式内容</param>
        /// <param name="isEdit">是否允许编辑</param>
        /// <param name="fjfa_dmmc">选择按钮弹出选择弹窗的内容表dm字段的分级规则,不传递则分级</param>
        /// <param name="dt_dmmc">选择按钮弹出选择弹窗的内容表（该表必须包含dm,mc这两个字段）</param>
        public Window_defineFormula(List<String> listConditionFileds, String gsnr, String displayGs, Boolean isEdit, String fjfa_dmmc, DataTable dt_dmmc)
        {
            InitializeComponent();
            this.dialog_dmmc = dt_dmmc;
            this.dialog_fjfa = (fjfa_dmmc.Trim().Length <= 0 ? "99" : fjfa_dmmc);
            if (dt_dmmc == null || dt_dmmc.Rows.Count <= 0)
            {
                this.btn_selectEle.Visibility = Visibility.Collapsed;
            }
            this.sb_conditon.Append(gsnr);
            this.IsEdit = isEdit;
            this.DataContext = this;
            initFields(listConditionFileds);
            initLuoJI_TiaoJian();
            initgs(displayGs, gsnr);
            if (!isEdit)
            {
                this.lbox_gs.IsEnabled = true;
                this.dg_guize.IsReadOnly = true;
                this.tbox_result.IsReadOnly = true;
                this.btn_addTiaoJian.IsEnabled = false;
                this.btn_delTiaoJian.IsEnabled = false;
                this.btn_add.IsEnabled = false;
                this.btn_del.IsEnabled = false;
                this.btn_up.IsEnabled = false;
                this.btn_down.IsEnabled = false;
                this.btn_cancel.IsEnabled = false;
                this.btn_ok.IsEnabled = false;
                this.btn_saveAndBack.IsEnabled = false;
            }
        }
        /// <summary>
        /// 公式设置弹窗，设置完成后返回公式,需要实现getBackGsxx返回公式内容，gsnr(后台解析的真正公式内容),displayGs(便于阅读显示的公式内容)
        /// </summary>
        /// <param name="listConditionFileds">字段列表</param>
        /// <param name="gsnr">后台解析的真正公式内容</param>
        /// <param name="displayGs">便于阅读显示的公式内容</param>
        /// <param name="isEdit">是否允许编辑</param>
        /// <param name="fjfa_dmmc">选择按钮弹出选择弹窗的内容表dm字段的分级规则,不传递则不分级</param>
        /// <param name="dt_dmmc">选择按钮弹出选择弹窗的内容表（该表必须包含dm,mc这两个字段）</param>
        public Window_defineFormula(Dictionary<String, String> dictionaryConditionFileds, String gsnr, String displayGs, Boolean isEdit, String fjfa_dmmc, DataTable dt_dmmc)
        {
            InitializeComponent();
            this.dialog_dmmc = dt_dmmc;
            this.dialog_fjfa = (fjfa_dmmc.Trim().Length <= 0 ? "99" : fjfa_dmmc);
            if (dt_dmmc == null || dt_dmmc.Rows.Count <= 0)
            {
                this.btn_selectEle.Visibility = Visibility.Collapsed;
            }
            this.sb_conditon.Append(gsnr);
            this.IsEdit = isEdit;
            this.DataContext = this;
            initFields(dictionaryConditionFileds);
            initLuoJI_TiaoJian();
            initgs(displayGs, gsnr);
            if (!isEdit)
            {
                this.lbox_gs.IsEnabled = true;
                this.dg_guize.IsReadOnly = true;
                this.tbox_result.IsReadOnly = true;
                this.btn_addTiaoJian.IsEnabled = false;
                this.btn_delTiaoJian.IsEnabled = false;
                this.btn_add.IsEnabled = false;
                this.btn_del.IsEnabled = false;
                this.btn_up.IsEnabled = false;
                this.btn_down.IsEnabled = false;
                this.btn_cancel.IsEnabled = false;
                this.btn_ok.IsEnabled = false;
                this.btn_saveAndBack.IsEnabled = false;
            }
        }
        //解析内容
        private void initgs(String displayGs, String gsnr)
        {
            try
            {
                this.lbox_gs.Items.Clear();
                if (gsnr.Length > 0)
                {
                    //一、多个条件的分割
                    List<String> list_gs = new List<string>();
                    List<String> list_gs_tmp = DefinedFormulaUtils.spliter(gsnr.ToString(), "&V];[F&", "&V]", "[F&");
                    foreach (String str in list_gs_tmp)
                    {
                        foreach (String str_tmp in DefinedFormulaUtils.spliter(str, "&V];:[V&", "&V]", ":[V&"))
                        {
                            list_gs.Add(str_tmp);
                        }
                    } 
                    //二、单个公式内容的字段 条件 逻辑关系的分割等等
                    int i = 0;
                    foreach (String singelGsStr in list_gs)
                    {
                        ListBoxItem lbi = new ListBoxItem();
                        lbi.Content = DefinedFormulaUtils.chaijieGSByJS(singelGsStr, "");
                        lbi.Tag = list_gs[i].ToString();
                        this.lbox_gs.Items.Add(lbi);
                        i++;
                    }
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show("初始化公式时失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        //双击公式后解析公式内容
        private void JieXieGsnr(String gsnr)
        {
            try
            {
                this.tbox_result.Text = "";
                this.List_MBGuiZe.Clear();
                if (!this.lbox_gs.IsEnabled) return;
                if (this.lbox_gs.SelectedItems.Count <= 0) return;
                String gsVal = "";
                gsVal = gsnr.Substring(gsnr.LastIndexOf(":[V&") + 1).Trim();//结果内容截取 
                gsnr = gsnr.Substring(0, gsnr.LastIndexOf(":[V&")).Trim();//公式内容截取 

                while (gsnr.Trim().Length > 0)
                {
                    //1、截取字段
                    String filed = gsnr.Substring((gsnr.IndexOf("[F&") + "[F&".Length), (gsnr.IndexOf("&F]") - (gsnr.IndexOf("[F&") + "[F&".Length)));
                    gsnr = gsnr.Substring((gsnr.IndexOf("&F]") + "&F]".Length));
                    foreach (ComboItemsResources cir in this.List_field)
                    {
                        if (cir.Dm.Equals(filed))
                        {
                            filed = cir.Mc;
                            break;
                        }
                    }
                    //2、条件
                    String tiaoJian = gsnr.Substring((gsnr.IndexOf("[T&") + "[T&".Length), (gsnr.IndexOf("&T]") - (gsnr.IndexOf("[T&") + "[T&".Length)));
                    gsnr = gsnr.Substring((gsnr.IndexOf("&T]") + "&T]".Length));
                    //3、条件值
                    String condition = gsnr.Substring((gsnr.IndexOf("[C&") + "[C&".Length), (gsnr.IndexOf("&C]") - (gsnr.IndexOf("[C&") + "[C&".Length)));
                    gsnr = gsnr.Substring((gsnr.IndexOf("&C]") + "&C]".Length));
                    //4、逻辑条件
                    String luoJi = gsnr.Substring((gsnr.IndexOf("[L&") + "[L&".Length), (gsnr.IndexOf("&L]") - (gsnr.IndexOf("[L&") + "[L&".Length)));
                    gsnr = gsnr.Substring((gsnr.IndexOf("&L]") + "&L]".Length));
                    this.List_MBGuiZe.Add(new MBGuiZe() { Field = filed, TiaoJian = tiaoJian, Val = condition, LuoJiGuanXi = luoJi });
                }
              
                //解析结果内容
                int ccc = 0;
                String valgs = gsVal.Substring(gsVal.IndexOf("[V&") + "[V&".Length, gsVal.LastIndexOf("&V]") - (gsVal.IndexOf("[V&") + "[V&".Length));

                while (valgs.Contains("[F&") && valgs.Contains("&F]"))
                {
                    //防止死循环
                    if (ccc > 10000) { break; }
                    ccc++;
                    String fieldName = valgs.Substring(valgs.IndexOf("[F&")+ "[F&".Length, valgs.IndexOf("&F]") - valgs.IndexOf("[F&")- "[F&".Length);
                    if (this.List_field == null || this.List_field.Count <= 0)
                    { 
                        valgs = valgs.Replace("[F&" + fieldName + "&F]", "{&" + fieldName + "&}");
                    }
                    else
                    {
                        Boolean hasExists = false;
                        foreach (ComboItemsResources cir in this.List_field)
                        {
                            if (("[F&" + cir.Dm + "&F]").Equals(fieldName))
                            {
                                valgs = valgs.Replace(fieldName, "{&" + cir.Mc + "&}");
                                hasExists = true;
                                break;
                            }
                        }
                        if (!hasExists) { 
                            valgs = valgs.Replace("[F&" + fieldName+ "&F]", "{&" + fieldName + "&}");
                        }
                    }
                }
                valgs = valgs.Replace("{&", "[").Replace("&}", "]");


                this.tbox_result.Text = valgs;
            }
            catch (Exception e1)
            {
                MessageBox.Show("解析公式时失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }

        }

        //初始化字段下拉框内容
        private void initFields(List<String> list_fileCol)
        {
            try
            {
                this.List_field.Clear();
                this.lbox_fields.Items.Clear();
                foreach (String dm in list_fileCol)
                {
                    ComboItemsResources cir = new ComboItemsResources();
                    cir.Dm = dm;
                    cir.Mc = dm;
                    cir.Dmmc = cir.Dm + "-" + cir.Mc;
                    ListBoxItem lbi = new ListBoxItem();
                    if (dm.Length > 0)
                    {
                        lbi.Content = "[" + cir.Mc + "]";
                        lbi.Tag = cir;
                        lbi.ToolTip = cir.Dm;
                        this.lbox_fields.Items.Add(lbi);
                    }
                    this.List_field.Add(cir);
                }
                this.dgcol_field.ItemsSource = List_field;
                this.dgcol_field.DisplayMemberPath = "Mc";
                this.dgcol_field.SelectedValuePath = "Dm";
                Binding binding = new Binding("Field");
                this.dgcol_field.TextBinding = binding;
            }
            catch (Exception e1)
            {
                MessageBox.Show("初始化字段失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        } //初始化字段下拉框内容
        private void initFields(Dictionary<String, String> list_fileCol)
        {
            try
            {
                this.List_field.Clear();
                this.lbox_fields.Items.Clear();
                foreach (String dm in list_fileCol.Keys)
                {
                    ComboItemsResources cir = new ComboItemsResources();
                    cir.Dm = dm;
                    String val = dm;
                    list_fileCol.TryGetValue(dm, out val);
                    cir.Mc = val;
                    cir.Dmmc = cir.Dm + "-" + cir.Mc;
                    ListBoxItem lbi = new ListBoxItem();
                    lbi.Content = "[" + cir.Mc + "]";
                    lbi.Tag = cir;
                    lbi.ToolTip = cir.Dm;
                    this.lbox_fields.Items.Add(lbi);
                    this.List_field.Add(cir);
                }
                this.dgcol_field.ItemsSource = List_field;
                this.dgcol_field.DisplayMemberPath = "Mc";
                this.dgcol_field.SelectedValuePath = "Dm";
                Binding binding = new Binding("Field");
                this.dgcol_field.TextBinding = binding;
            }
            catch (Exception e1)
            {
                MessageBox.Show("初始化字段失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //初始化条件下拉框及逻辑关系下拉框内容
        private void initLuoJI_TiaoJian()
        {
            try
            {
                List_tiaoJian.Clear();
                List_tiaoJian.Add(new ComboItemsResources { Dm = "<", Mc = "<", Dmmc = "<" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "<=", Mc = "<=", Dmmc = "<=" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = ">", Mc = ">", Dmmc = ">" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = ">=", Mc = ">=", Dmmc = ">=" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "=", Mc = "=", Dmmc = "=" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "<>", Mc = "<>", Dmmc = "<>" });
                //List_tiaoJian.Add(new ComboItemsResources { Dm = "start", Mc = "start", Dmmc = "start" });
                //List_tiaoJian.Add(new ComboItemsResources { Dm = "end", Mc = "end", Dmmc = "end" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "startWith", Mc = "startWith", Dmmc = "startWith" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "contains", Mc = "contains", Dmmc = "contains" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "notContains", Mc = "notContains", Dmmc = "notContains" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "length<=", Mc = "length<=", Dmmc = "length<=" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "length>=", Mc = "length>=", Dmmc = "length>=" });
                List_tiaoJian.Add(new ComboItemsResources { Dm = "length!=", Mc = "length!=", Dmmc = "length!=" });
                this.dgcol_tiaoJian.ItemsSource = List_tiaoJian;
                this.dgcol_tiaoJian.DisplayMemberPath = "Dm";
                this.dgcol_tiaoJian.SelectedValuePath = "Dmmc";
                Binding binding_ljgx = new Binding("TiaoJian");
                this.dgcol_tiaoJian.TextBinding = binding_ljgx;

                List_luoJiGuanXi.Clear();
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "", Dmmc = "", Mc = "" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "(", Dmmc = "(", Mc = "(" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = ")", Dmmc = ")", Mc = ")" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "and", Dmmc = "并且", Mc = "并且" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "or", Dmmc = "或者", Mc = "或者" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = ")and", Dmmc = ")并且", Mc = ")并且" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "and(", Dmmc = "并且(", Mc = "并且(" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = ")or", Dmmc = ")或者", Mc = ")或者" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = "or(", Dmmc = "或者(", Mc = "或者(" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = ")and(", Dmmc = ")并且(", Mc = ")并且(" });
                List_luoJiGuanXi.Add(new ComboItemsResources { Dm = ")or(", Dmmc = ")或者(", Mc = ")或者(" });
                this.dgcol_luoJiGuanXi.ItemsSource = List_luoJiGuanXi;
                this.dgcol_luoJiGuanXi.DisplayMemberPath = "Dm";
                this.dgcol_luoJiGuanXi.SelectedValuePath = "Dmmc";
                Binding binding = new Binding("LuoJiGuanXi");
                this.dgcol_luoJiGuanXi.TextBinding = binding;
            }
            catch (Exception e1)
            {
                MessageBox.Show("初始化条件及逻辑关系失败，错误信息：" + e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        //增加一个条件的按钮
        private void btn_add_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                //添加行
                ListBoxItem lbi = new ListBoxItem();
                lbi.Content = "";
                lbi.Tag = "";
                this.lbox_gs.Items.Add(lbi);
                this.lbox_gs.SelectedItem = lbi;
                this.lbox_gs.IsEnabled = false;
                //设置控件状态
                this.lbox_gs.IsEnabled = false;
                this.dg_guize.IsReadOnly = false;
                this.tbox_result.IsReadOnly = false;
                this.btn_addTiaoJian.IsEnabled = true;
                this.btn_delTiaoJian.IsEnabled = true;
                this.btn_add.IsEnabled = false;
                this.btn_del.IsEnabled = false;
                this.btn_up.IsEnabled = false;
                this.btn_down.IsEnabled = false;
                this.btn_cancel.IsEnabled = true;
                this.btn_ok.IsEnabled = true;
                this.btn_saveAndBack.IsEnabled = false;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        //增加按钮事件
        private void btn_addTiaoJian_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                ObservableCollection<ComboItemsResources> list_MBGuiZes = new ObservableCollection<ComboItemsResources>();
                foreach (ComboItemsResources mbGuiZe in this.List_luoJiGuanXi)
                {
                    list_MBGuiZes.Add(mbGuiZe.Clone() as ComboItemsResources);
                }
                List_MBGuiZe.Add(new MBGuiZe { Xh = this.List_MBGuiZe.Count + 1, List_LuoJiGuanXi = list_MBGuiZes });
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        //确认按钮事件
        private void btn_ok_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                StringBuilder displayConditon = new StringBuilder("");//显示公式
                StringBuilder conditon = new StringBuilder("");//实际公式内容
                int i = 0;
                //检测逻辑关系的的括号是否匹配
                int countPreKuoHao = 0; //前括号数量
                int countFixKuoHao = 0; //后括号数量
                foreach (MBGuiZe mbGuiZe in this.List_MBGuiZe)
                {
                    i++;
                    if (mbGuiZe.LuoJiGuanXi.Contains("("))
                    {
                        countPreKuoHao++;
                    }
                    if (mbGuiZe.LuoJiGuanXi.Contains(")"))
                    {
                        countFixKuoHao++;
                    }
                    //检查公式规则内容
                    if (mbGuiZe.Field.Equals(""))
                    {
                        throw new Exception("公式检查未通过，第 " + i + " 行的字段内容为空，修改后重试！");
                    }
                    if (mbGuiZe.TiaoJian.Equals(""))
                    {
                        throw new Exception("公式检查未通过，第 " + i + " 行的条件内容为空，修改后重试！");
                    }
                    if (mbGuiZe.Val.Equals(""))
                    {
                        throw new Exception("公式检查未通过，第 " + i + " 行的值内容为空，修改后重试！");
                    }
                    if (i < this.List_MBGuiZe.Count && mbGuiZe.LuoJiGuanXi.Equals(""))
                    {
                        throw new Exception("公式检查未通过，第 " + i + " 行的逻辑关系内容为空，修改后重试！");
                    }
                    //显示公式
                    displayConditon.Append("" + mbGuiZe.Field + " " + mbGuiZe.TiaoJian + " " + mbGuiZe.Val + " " + mbGuiZe.LuoJiGuanXi + " ");
                    //实际公式
                    String field = mbGuiZe.Field;
                    foreach (ComboItemsResources cir in this.List_field)
                    {
                        if (cir.Mc.Equals(mbGuiZe.Field))
                        {
                            field = cir.Dm;
                            break;
                        }
                    }
                    conditon.Append("[F&" + field + "&F][T&" + mbGuiZe.TiaoJian + "&T][C&" + mbGuiZe.Val + "&C][L&" + mbGuiZe.LuoJiGuanXi + "&L]");
                }
                if (countFixKuoHao - countPreKuoHao != 0)
                {
                    throw new Exception("公式检查未通过，逻辑关系中的括号前后括号不匹配");
                }
                if (!conditon.ToString().Equals("") && !conditon.ToString().EndsWith("[L&&L]") && !conditon.ToString().EndsWith("[L&)&L]"))
                {
                    throw new Exception("公式检查未通过，逻辑关系中最后一行只能以\")\"或空结尾");
                }
                displayConditon.Insert(0, "if (");
                displayConditon.Append(")");
                int ccc = 0;
                String valgs = this.tbox_result.Text;
                while (valgs.Contains("[") && valgs.Contains("]"))
                {
                    //防止死循环
                    if (ccc > 10000) { break; }
                    ccc++;
                    String fieldName = valgs.Substring(valgs.IndexOf("["), valgs.IndexOf("]") - valgs.IndexOf("[")) + "]";

                    foreach (ComboItemsResources cir in this.List_field)
                    {
                        if (("[" + cir.Mc + "]").Equals(fieldName))
                        {
                            valgs = valgs.Replace(fieldName, "" + cir.Mc + "");
                            break;
                        }
                    }
                }
                displayConditon.Append("{" + valgs + "}");
                valgs = this.tbox_result.Text;
                //处理计算结果公式字段。
                while (valgs.Contains("[") && valgs.Contains("]"))
                {
                    //防止死循环
                    if (ccc > 10000) { break; }
                    ccc++;
                    String fieldName = valgs.Substring(valgs.IndexOf("["), valgs.IndexOf("]") - valgs.IndexOf("[")) + "]";
                    foreach (ComboItemsResources cir in this.List_field)
                    {
                        if (("[" + cir.Mc + "]").Equals(fieldName))
                        {
                            valgs = valgs.Replace(fieldName, "{&" + cir.Dm + "&}");
                            break;
                        }
                    }
                }
                valgs = valgs.Replace("{&", "[F&").Replace("&}", "&F]");
                conditon.Append(":[V&" + valgs + "&V]");

                ListBoxItem lbi = (this.lbox_gs.SelectedItem as ListBoxItem);
                lbi.Tag = conditon.ToString();
                lbi.Content = DefinedFormulaUtils.chaijieGSByJS(conditon.ToString(), "");
                //设置控件内容
                this.lbox_gs.IsEnabled = true;
                this.dg_guize.IsReadOnly = true;
                this.tbox_result.IsReadOnly = true;
                this.btn_addTiaoJian.IsEnabled = false;
                this.btn_delTiaoJian.IsEnabled = false;
                this.btn_add.IsEnabled = true;
                this.btn_del.IsEnabled = true;
                this.btn_up.IsEnabled = true;
                this.btn_down.IsEnabled = true;
                this.btn_cancel.IsEnabled = false;
                this.btn_ok.IsEnabled = false;
                this.btn_saveAndBack.IsEnabled = true;
                /*
                 * foreach (ListBoxItem lbi_ in this.lbox_gs.Items)
                {
                    lbi_.Content = "（" + (this.lbox_gs.Items.IndexOf(lbi_) + 1) + "）" + lbi_.Tag.ToString().Replace("&][&", " ");
                }
                */
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, "提示", MessageBoxButton.OK, MessageBoxImage.Information);
            }
        }

        private void lbox_gs_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            if (this.lbox_gs.SelectedItem == null)
            {
                return;
            }
            else
            {
                ListBoxItem lbi = this.lbox_gs.SelectedItems[0] as ListBoxItem;
                JieXieGsnr(lbi.Tag.ToString());
                if (IsEdit)
                {
                    this.lbox_gs.IsEnabled = false;
                    this.dg_guize.IsReadOnly = false;
                    this.tbox_result.IsReadOnly = false;
                    this.btn_addTiaoJian.IsEnabled = true;
                    this.btn_delTiaoJian.IsEnabled = true;
                    this.btn_add.IsEnabled = false;
                    this.btn_del.IsEnabled = false;
                    this.btn_up.IsEnabled = false;
                    this.btn_down.IsEnabled = false;
                    this.btn_cancel.IsEnabled = true;
                    this.btn_ok.IsEnabled = true;
                    this.btn_saveAndBack.IsEnabled = false;
                }
                else
                {
                    this.lbox_gs.IsEnabled = true;
                    this.dg_guize.IsReadOnly = true;
                    this.tbox_result.IsReadOnly = true;
                    this.btn_addTiaoJian.IsEnabled = false;
                    this.btn_delTiaoJian.IsEnabled = false;
                    this.btn_add.IsEnabled = false;
                    this.btn_del.IsEnabled = false;
                    this.btn_up.IsEnabled = false;
                    this.btn_down.IsEnabled = false;
                    this.btn_cancel.IsEnabled = false;
                    this.btn_ok.IsEnabled = false;
                    this.btn_saveAndBack.IsEnabled = false;
                }
            }
        }

        private void btn_delTiaoJian_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (this.dg_guize.SelectedCells.Count > 0)
                {
                    this.List_MBGuiZe.Remove((this.dg_guize.SelectedCells[0].Item as MBGuiZe));
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void btn_cancel_Click(object sender, RoutedEventArgs e)
        {
            //设置控件内容
            this.lbox_gs.IsEnabled = true;
            this.dg_guize.IsReadOnly = true;
            this.tbox_result.IsReadOnly = true;
            this.btn_addTiaoJian.IsEnabled = false;
            this.btn_delTiaoJian.IsEnabled = false;
            this.btn_add.IsEnabled = true;
            this.btn_del.IsEnabled = true;
            this.btn_up.IsEnabled = true;
            this.btn_down.IsEnabled = true;
            this.btn_cancel.IsEnabled = false;
            this.btn_ok.IsEnabled = false;
            this.btn_saveAndBack.IsEnabled = true;
        }

        //点击完成按钮后
        private void btn_saveAndBack_Click(object sender, RoutedEventArgs e)
        {
            if (!this.btn_ok.IsEnabled)
            {
                if (this.getBackGsxx != null)
                {
                    this.Sb_conditon.Clear();
                    this.Sb_gsForDisplay.Clear();
                    foreach (ListBoxItem lbi in this.lbox_gs.Items)
                    {
                        if (lbi.Tag.ToString().Length <= 0)
                        {
                            continue;
                        }
                        else
                        {
                            this.Sb_conditon.Append(((this.Sb_conditon.Length > 0) ? ";" : "") + lbi.Tag.ToString());
                            String gsDisplay = lbi.Content.ToString();
                            this.Sb_gsForDisplay.Append(((this.Sb_gsForDisplay.Length > 0) ? ";" : "") + gsDisplay);
                        }
                    }
                    this.IsOk = true;
                    if (this.getBackGsxx(this.Sb_conditon.ToString(), this.Sb_gsForDisplay.ToString()))
                    {
                        this.Close();
                    }
                    else
                    {
                        MessageBox.Show("公式未正常返回！");
                    }
                }
                else
                {
                    this.Sb_conditon.Clear();
                    this.Sb_gsForDisplay.Clear();
                    foreach (ListBoxItem lbi in this.lbox_gs.Items)
                    {
                        if (lbi.Tag.ToString().Length <= 0)
                        {
                            continue;
                        }
                        else
                        {
                            this.Sb_conditon.Append(((this.Sb_conditon.Length > 0) ? ";" : "") + lbi.Tag.ToString());
                            String gsDisplay = lbi.Content.ToString();
                            this.Sb_gsForDisplay.Append(((this.Sb_gsForDisplay.Length > 0) ? ";" : "") + gsDisplay);
                        }
                    }
                    this.IsOk = true;
                    this.Close();
                }
            }
        }

        private void btn_up_Click(object sender, RoutedEventArgs e)
        {
            if (this.lbox_gs.IsEnabled && this.lbox_gs.SelectedItems.Count > 0)
            {
                int i = 0;
                ListBoxItem lbi = (this.lbox_gs.SelectedItem as ListBoxItem);
                i = this.lbox_gs.Items.IndexOf(lbi);
                this.lbox_gs.Items.Remove(lbi);
                this.lbox_gs.Items.Insert((i - 1 <= 0 ? 0 : i - 1), lbi);
                this.lbox_gs.SelectedItem = lbi;
            }
        }

        private void btn_down_Click(object sender, RoutedEventArgs e)
        {
            if (this.lbox_gs.IsEnabled && this.lbox_gs.SelectedItems.Count > 0)
            {
                int i = this.lbox_gs.Items.Count;
                ListBoxItem lbi = (this.lbox_gs.SelectedItem as ListBoxItem);
                i = this.lbox_gs.Items.IndexOf(lbi);
                this.lbox_gs.Items.Remove(lbi);
                if (i + 1 >= this.lbox_gs.Items.Count && this.lbox_gs.Items.Count - 1 >= 0)
                {
                    i = this.lbox_gs.Items.Count;
                }
                else
                {
                    i++;
                }
                this.lbox_gs.Items.Insert(i, lbi);
                this.lbox_gs.SelectedItem = lbi;
            }
        }

        private void btn_del_Click(object sender, RoutedEventArgs e)
        {
            if (this.lbox_gs.IsEnabled && this.lbox_gs.SelectedItems.Count > 0)
            {
                int i = 0;
                ListBoxItem lbi = (this.lbox_gs.SelectedItem as ListBoxItem);
                i = this.lbox_gs.Items.IndexOf(lbi);
                i--;
                this.lbox_gs.Items.Remove(lbi);
                this.lbox_gs.SelectedIndex = i;
            }
        }

        //字段双击事件
        private void lbox_fields_MouseDoubleClick(object sender, MouseButtonEventArgs e)
        {
            try
            {
                if (this.lbox_fields.SelectedItem == null || !this.IsEdit) return;
                if (!this.btn_ok.IsEnabled) return;
                int index = this.tbox_result.SelectionStart; //当前光标位置
                int cursorIndex = 0;//记录后续的光标位置
                String selectTxt = this.tbox_result.SelectedText;//选中内容
                String text = this.tbox_result.Text;//文本框内容
                StringBuilder val = new StringBuilder("");
                ListBoxItem lbi = (this.lbox_fields.SelectedItem as ListBoxItem);
                String str = lbi.Content.ToString();//点击项的内容

                if (selectTxt != null && selectTxt.Length > 0)
                {
                    val.Append(str);
                    val.Append(text.Substring(index + selectTxt.Length));
                    cursorIndex = index + str.Length;
                }
                else if (index >= 0)
                {
                    val.Append(text.Substring(0, index));
                    val.Append(str);
                    val.Append(text.Substring(index + selectTxt.Length));
                    cursorIndex = index + str.Length;
                }
                else
                {
                    val.Append(text);
                    val.Append(str);
                    cursorIndex = (val.Length > 0 ? 0 : -1);
                }
                this.tbox_result.Text = val.ToString();
                this.tbox_result.SelectionStart = cursorIndex;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }

        private void btn_jisuan_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                Button btn = sender as Button;
                if (!this.IsEdit) return;
                if (!this.btn_ok.IsEnabled) return;
                int index = this.tbox_result.SelectionStart; //当前光标位置
                int cursorIndex = 0;//记录后续的光标位置
                String selectTxt = this.tbox_result.SelectedText;//选中内容
                String text = this.tbox_result.Text;//文本框内容
                StringBuilder val = new StringBuilder("");
                String str = btn.Tag.ToString();//点击项的内容

                if (selectTxt != null && selectTxt.Length > 0)
                {
                    val.Append(str);
                    val.Append(text.Substring(index + selectTxt.Length));
                    cursorIndex = index + str.Length;
                }
                else if (index >= 0)
                {
                    val.Append(text.Substring(0, index));
                    val.Append(str);
                    val.Append(text.Substring(index + selectTxt.Length));
                    cursorIndex = index + str.Length;
                }
                else
                {
                    val.Append(text);
                    val.Append(str);
                    cursorIndex = (val.Length > 0 ? 0 : -1);
                }
                this.tbox_result.Text = val.ToString();
                this.tbox_result.SelectionStart = cursorIndex;
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message);
            }
        }
        //弹窗选择内容 
        private void btn_selectEle_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                if (!isEdit) return;
                //String result = "";
                //String sql_fjfa = "select '1-3'+substring(kmbmfa,2,20) as fzfa from gl_ztcs  where hsdwdm = '" + LoginInfo.getInstance().Hsdwdm + "' and ztbh = '" + LoginInfo.getInstance().SelectedZTDM + "' and kjnd = '" + LoginInfo.getInstance().Dywrq.Year + "'";
                //String fjfa = "";
                //DataSet ds_fjfa = Dao.getSql(sql_fjfa, "gl_ztcs", out result);
                //if (ds_fjfa != null && ds_fjfa.Tables.Count > 0 && ds_fjfa.Tables[0].Rows.Count > 0)
                //{
                //    fjfa = ds_fjfa.Tables[0].Rows[0][0].ToString();
                //}
                Dialog_TreeDMMC dia_xmxx = new Dialog_TreeDMMC();
                dia_xmxx.Title = "选择";
                //String sql_query = "select kmdm as dm,replace(replace(kmmc,'>','&gt;'),'<','&lt;') as mc from gl_kmxx where gsdm = '" + LoginInfo.getInstance().Hsdwdm + "' and zth = '" + LoginInfo.getInstance().SelectedZTDM + "' and kjnd = '" + LoginInfo.getInstance().Dywrq.Year + "' union all select '1','资产类' union all select '2','负债类' union all select '3','净资产类' union all select '4','收入类' union all select '5','费用类' union all select '6','预算收入' union all select '7','预算支出' union all select '8','预算结余'  order by dm";
                //DataSet ds = Dao.getSql(sql_query, "gl_kmzl", out result); 
                dia_xmxx.iniData(dialog_fjfa, '-', dialog_dmmc, "dm", "mc");
                dia_xmxx.WindowStartupLocation = WindowStartupLocation.CenterScreen;
                dia_xmxx.ShowDialog();
                if (!dia_xmxx.Dm.Equals(""))
                {
                    int index = this.tbox_result.SelectionStart; //当前光标位置
                    int cursorIndex = 0;//记录后续的光标位置
                    String selectTxt = this.tbox_result.SelectedText;//选中内容
                    String text = this.tbox_result.Text;//文本框内容
                    StringBuilder val = new StringBuilder("");
                    String str = "'" + dia_xmxx.Dm + "'";//点击项的内容

                    if (selectTxt != null && selectTxt.Length > 0)
                    {
                        val.Append(str);
                        val.Append(text.Substring(index + selectTxt.Length));
                        cursorIndex = index + str.Length;
                    }
                    else if (index >= 0)
                    {
                        val.Append(text.Substring(0, index));
                        val.Append(str);
                        val.Append(text.Substring(index + selectTxt.Length));
                        cursorIndex = index + str.Length;
                    }
                    else
                    {
                        val.Append(text);
                        val.Append(str);
                        cursorIndex = (val.Length > 0 ? 0 : -1);
                    }
                    this.tbox_result.Text = val.ToString();
                    this.tbox_result.SelectionStart = cursorIndex;
                }
            }
            catch (Exception e1)
            {
                MessageBox.Show(e1.Message, "错误", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }
    }
}
